package com.jf3q.admin.utils.filter;

import com.alibaba.fastjson.JSON;
import com.jf3q.admin.entity.User;
import com.jf3q.admin.service.impl.UserServiceImpl;
import com.jf3q.admin.utils.JwtUtil;
import com.jf3q.admin.utils.vo.AjaxResultVO;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author ASUS
 * @date 2024/4/13
 * @apiNote
 */
@AllArgsConstructor
public class TokenFilter extends OncePerRequestFilter {


    UserServiceImpl userService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            String token = request.getHeader("token");
            String username = JwtUtil.getUsername(token);
            User user = (User) userService.loadUserByUsername(username);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword(), user.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            filterChain.doFilter(request,response);
        } catch (Exception e) {
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(AjaxResultVO.error(514,"token.error:"+e.getMessage())));
            writer.flush();
            writer.close();
            doFilter(request,response,filterChain);
        }
    }
}
